from itertools import groupby

from _decimal import Decimal
from flask import Blueprint, request, render_template, flash, redirect, url_for, jsonify
from datetime import datetime
from models import db, SalesOrderModel, ProductModel, MemberModel, ProductSalesOrderModel
from decorators import login_req, login_required
bp = Blueprint("sale", __name__, url_prefix="/sale")

@bp.route("/", methods=['GET'])
@login_required
def saleorders():
    saleorders = SalesOrderModel.query.all()
    result = []
    for saleorder in saleorders:
        saleorder_data = {
            'id': saleorder.id,
            'member_name': saleorder.member.name,
            'time': saleorder.sales_time,
            'status': saleorder.status,
            'total_amount': saleorder.total_amount,
        }
        result.append(saleorder_data)
    return render_template("销售管理.html", sales_orders=result)

@bp.route("/shopping_cart", methods=['GET'])
@login_required
def shoppingcart():
    sales_order_unfinish=SalesOrderModel.query.filter_by(status=False).all()
    for x in sales_order_unfinish:
        db.session.delete(x)


    sales_order = SalesOrderModel( member_id=2,sales_time=datetime.now(), total_amount=0)
    db.session.add(sales_order)

    db.session.commit()
    sales_order_id=sales_order.id
    return render_template("新增销售订单.html",sales_order_id=sales_order_id)

@bp.route("/shopping_cart", methods=['POST'])
@login_required
def shoppingcart_add():
    product_id = request.form.get('product_id')
    product=ProductModel.query.get(product_id)
    sales_quantity = request.form.get('quantity')
    sales_order_id = request.form.get('sales_order_id')
    amount=float(product.price)*float(sales_quantity)
    product_sales_order=ProductSalesOrderModel(product_id=product_id,sales_quantity=sales_quantity,salesorder_id=sales_order_id,amount=amount)
    db.session.add(product_sales_order)

    product_sales_orders=ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id)
    sales_order=SalesOrderModel.query.get(sales_order_id)
    total_amount=0
    for x in product_sales_orders:
        total_amount+=float(x.amount)
    sales_order.total_amount=total_amount

    db.session.commit()

    #获取购物车中信息
    cart_items = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id).all()

    return render_template("新增销售订单.html",
                           sales_order_id=sales_order_id,
                           cart_items=cart_items,
                           member_phone=sales_order.member.mobile,
                           total_amount=sales_order.total_amount)

@bp.route("/shopping_cart/manage", methods=['POST'])
@login_required
def shoppingcart_manage():
    sales_order_id = request.form.get('sales_order_id')
    product_sales_order_id = request.form.get('item_id')
    new_sales_quantity = request.form.get('new_quantity')
    product_salesorder=ProductSalesOrderModel.query.get(product_sales_order_id)
    product_salesorder.sales_quantity=new_sales_quantity
    #更改总金额
    product_salesorder.amount=float(product_salesorder.product.price)*float(product_salesorder.sales_quantity)

    product_sales_orders=ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id)
    sales_order=SalesOrderModel.query.get(sales_order_id)
    total_amount=0
    for x in product_sales_orders:
        total_amount+=float(x.amount)
    sales_order.total_amount=total_amount


    db.session.commit()

    cart_items = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id).all()
    return render_template("新增销售订单.html",
                           sales_order_id=sales_order_id,
                           cart_items=cart_items,
                           member_phone=sales_order.member.mobile,
                           total_amount=sales_order.total_amount)
@bp.route("/shopping_cart/delete", methods=['POST'])
@login_required
def shoppingcart_delete():
    sales_order_id = request.form.get('sales_order_id')
    product_sales_order_id = request.form.get('item_id')
    product_salesorder=ProductSalesOrderModel.query.get(product_sales_order_id)
    if product_salesorder:

        db.session.delete(product_salesorder)

        product_sales_orders = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id)
        sales_order = SalesOrderModel.query.get(sales_order_id)
        total_amount = 0
        for x in product_sales_orders:
            total_amount += float(x.amount)
        sales_order.total_amount = total_amount

        db.session.commit()

    cart_items = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id).all()
    return render_template("新增销售订单.html",
                           sales_order_id=sales_order_id,
                           cart_items=cart_items,
                           member_phone=sales_order.member.mobile,
                           total_amount=sales_order.total_amount)

@bp.route("/shopping_cart/update_memberphone", methods=['POST'])
@login_required
def update_salesorder_memberphone():
    sales_order_id = request.form.get('sales_order_id')
    member_phone = request.form.get('member_phone')
    member = MemberModel.query.filter_by(mobile=member_phone).first()
    sales_order=SalesOrderModel.query.get(sales_order_id)
    if member:
        sales_order.member_id=member.id
        db.session.commit()
    cart_items = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id).all()

    return render_template("新增销售订单.html",
                           sales_order_id=sales_order_id,
                           cart_items=cart_items,
                           member_phone=sales_order.member.mobile,
                           total_amount=sales_order.total_amount)


@bp.route("/shopping_cart/save/<sales_order_id>")
@login_required
def shoppingcart_save(sales_order_id):
    product_sales_orders=ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id)
    total_amount=0
    for x in product_sales_orders:
        total_amount+=x.amount
        x.product.stock_quantity=x.product.stock_quantity-x.sales_quantity
    sales_orders=SalesOrderModel.query.get(sales_order_id)
    sales_orders.status=True
    sales_orders.total_amount=total_amount
    sales_orders.member.points+=total_amount

    db.session.commit()
    return redirect(url_for("sale.shoppingcart"))

@bp.route("/shoppingcart/display/<sales_order_id>/", methods=['GET'])
@login_required
def shoppingcart_display(sales_order_id):
    sales_order=SalesOrderModel.query.get(sales_order_id)
    cart_items = ProductSalesOrderModel.query.filter_by(salesorder_id=sales_order_id).all()
    return render_template("新增销售订单.html",
                           sales_order_id=sales_order_id,
                           cart_items=cart_items,
                           member_phone=sales_order.member.mobile,
                           total_amount=sales_order.total_amount)


@bp.route("/delete", methods=['POST'])
@login_required
def delete_sales_order():
    sales_order_id = request.form.get('sales_order_id')
    sales_order=SalesOrderModel.query.get(sales_order_id)
    if sales_order:
        db.session.delete(sales_order)
        db.session.commit()
        flash('销售记录删除成功', 'success')
    else:
        flash('销售记录不存在', 'error')

    return redirect(url_for('sale.saleorders'))


@bp.route('/search_sales_orders', methods=['GET'])
@login_required
def search_purchase_orders():
    search_text = request.args.get('search')  # 获取查询字符串中的搜索关键字
    result = []
    if search_text:
        members = MemberModel.query.filter(MemberModel.name.ilike(f"%{search_text}%")).all()

        for member in members:
            sales_orders=SalesOrderModel.query.filter_by(member_id=member.id).all()
            for sales_order in sales_orders:
                sales_order_data={
                    'id': sales_order.id,
                    'member_name': sales_order.member.name,
                    'time': sales_order.sales_time,
                    'total_amount': sales_order.total_amount,
                }
                result.append(sales_order_data)
    else:
        sales_orders = SalesOrderModel.query.all()
        for sales_order in sales_orders:
            sales_order_data = {
                'id': sales_order.id,
                'member_name': sales_order.member.name,
                'time': sales_order.sales_time,
                'total_amount': sales_order.total_amount,
            }
            result.append(sales_order_data)
    return render_template("销售管理.html", sales_orders=result)

@bp.route('/sales_orders_analysis')
def sales_orders_analysis():
    sales_orders = SalesOrderModel.query.all()
    # 按日期对销售订单进行分组
    sales_orders_grouped = groupby(sales_orders, lambda order: order.sales_time.date())
    sales_data = []

    for date, orders in sales_orders_grouped:
        # 统计每个日期的销售单数和总销售金额
        count=0
        total_amount=0
        for order in orders:
            count+=1
            total_amount += order.total_amount
        sales_data.append({
            'date': str(date),
            'count': count,
            'total_amount': float(total_amount)
        })
    return jsonify(sales_data)

@bp.route('/analysis')
def display_analysis():
    return render_template("统计分析.html")

